import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { 
  CallToolRequestSchema,
  ListToolsRequestSchema 
} from '@modelcontextprotocol/sdk/types.js';
import {browserManager} from './browserManager.js'; 

class ToolHandler
{
    constructor(browserManagerInstance)
    {
        this.tools = browserManagerInstance.getTools() ;
        this.handlers = {} ;
        for(const tool of this.tools) this.handlers[tool.name] = tool.functionRef; 
    }

    async getListOfTools()
    {
        return {tools: this.tools} ;
    }

    async callTool(name, args)
    {
        const handler = this.handlers[name] ;
        if(!handler) return {content: [{type: "Text", text: "Unknown Tool " + name}]} ;
        const result = await handler(args) ;
        return {content: [{type: 'text', text: JSON.stringify(result)}]};
    }
}

async function initilizeServer(toolHandler)
{
    const server = new Server({name: "simple-playwright-server", version: "1.0.0"}, { capabilities: {tools: {}}});

    server.setRequestHandler(ListToolsRequestSchema, async () => {
        console.error("received list tools req") ;
        return await toolHandler.getListOfTools();
    });

    server.setRequestHandler(CallToolRequestSchema, async(request) => {
        if(!request.params.arguments) request.params.arguments = {} ;
        const {name, arguments: args} = request.params;
        console.error(`call tool request ${name}, ${JSON.stringify(args,null)} `) ;
        /// make it so when args is not in the request we make it {} empty JSON.
        return await toolHandler.callTool(name, args) ;
    })

    const transport = new StdioServerTransport();
    await server.connect(transport);
    
    return server; 
}

async function freeResources(server, browserManagerInstance)
{
    function sleep(seconds) {
        return new Promise(resolve => setTimeout(resolve, seconds * 1000));
    }
    await sleep(60*10) ;
    await browserManagerInstance.close() ;
    await server.close() ;
}

console.error("init browser") ;

const browserManagerInstance = await browserManager.create() ;

const toolHandler = new ToolHandler(browserManagerInstance) ;

const server = await initilizeServer(toolHandler) ;



await freeResources(server,browserManagerInstance) ;
